package cc.android.testapp.ui.part;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.TextView;

import cc.android.testapp.R;
import cc.android.testapp.ui.inject.InjectView;
import cc.android.testapp.ui.inject.ViewInject;
import cc.android.testapp.util.CLog;

public class CNumbEdit extends FrameLayout implements View.OnClickListener {
    @InjectView(id = R.id.tv_numb_title)
    protected TextView mTitle;
    @InjectView(id = R.id.btn_amount_add, addClickListener = true)
    protected ImageButton mBtn_increase;
    @InjectView(id = R.id.btn_amount_reduce, addClickListener = true)
    protected ImageButton mBtn_reduce;
    @InjectView(id = R.id.et_amount)
    protected EditText mEt_Numb;
    protected int mStepping = 1;
    protected int mNumb = 0;
    protected String mFormatStr;
    protected View mContent;

    public CNumbEdit(Context context, AttributeSet pAttrs) {
        super(context, pAttrs);

        CLog.log("生成CNumbEdit");
        LayoutInflater inflater = LayoutInflater.from(context);
        View tContent = inflater.inflate(R.layout.c_numb_edittext, null);
        this.mContent = tContent;
        this.addView(tContent);

        ViewInject.injectView(this, this::findViewById, this);

        TypedArray tTr = context.obtainStyledAttributes(pAttrs, R.styleable.CNumbEdit);
        setTitle(tTr.getString(R.styleable.CNumbEdit_title));
        setDefNumb(tTr.getInt(R.styleable.CNumbEdit_defNumb, 0));
        this.mStepping = tTr.getInt(R.styleable.CNumbEdit_stepping, 1);
        this.mFormatStr = tTr.getString(R.styleable.CNumbEdit_formatStr);
        tTr.recycle();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }

    public void increaseNumb() {
        this.mNumb += this.mStepping;
        this.onNumbChange();
    }

    public void reduceNumb() {
        this.mNumb -= this.mStepping;
        if (this.mNumb < 0) this.mNumb = 0;
        this.onNumbChange();
    }

    public int getNumb() {
        return this.mNumb;
    }

    public void setTitle(String pTitle) {
        if (pTitle == null) pTitle = "";
        this.mTitle.setText(pTitle);
    }

    public void setDefNumb(int pNumb) {
        this.mNumb = Math.max(pNumb, 0);
        this.onNumbChange();
    }

    public void onNumbChange() {
        this.mEt_Numb.setText(this.mNumb + "");
        this.invalidate();
    }

    public String getFormatStr() {
        if (this.mNumb == 0) return "";
        return String.format(this.mFormatStr, this.mNumb);
    }

    @Override
    public void onClick(View pView) {
        if (pView == this.mBtn_increase) this.increaseNumb();
        else if (pView == this.mBtn_reduce) this.reduceNumb();
    }
}
